#include <QMutexLocker>
#include <QDir>
#include <QTextStream>
#include <QApplication>
#include <QWidget>
#include <QSettings>
#include <QTextCodec>

#include <themes_manager/qls_themes_manager.h>

/* 主题管理系统 */
QLsThemesManager::QLsThemesManager(QObject *parent) : QObject(parent)
{
    /* 初始化当前主题 */
    QSettings settings("ini/themes.ini", QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("UTF-8"));
    m_curTheme = settings.value("cur/theme", "white").toString();
}

QLsThemesManager::QLsThemesManager(QString themesDir, QObject *parent)
    : QObject(parent), m_themesDir(themesDir),
      m_themesIniDir(QString("ini/%1.ini").arg(themesDir))
{
    /* 初始化可用主题列表 */
    RefreshLocalThemes();
}

/* 更新本地主题 */
void QLsThemesManager::RefreshLocalThemes()
{
    /* 清空上次记录 */
    m_themesList.clear();

    /* 打开本地主题文件夹 */
    QDir themesDir = QDir(qApp->applicationDirPath());
    if (!themesDir.cd(m_themesDir))
        return;
    foreach (QString filename, themesDir.entryList(QDir::Files)) {
        /* 获取qss主题样式文件 */
        if (!filename.endsWith(".qss"))
            continue;

        /* 加入列表 */
        m_themesList.append(filename.mid(0, filename.size() - 4));
    }
}

/* 加载主题 */
bool QLsThemesManager::LoadTheme(QWidget *widget, const QString &themeName)
{
    /* 判断当前主题是否存在 或 有无变化 */
    if (!m_themesList.contains(themeName) || m_curTheme == themeName)
        return false;

    /* 判断主题文件夹和判断当前主题文件是否存在 */
    QDir themesDir = QDir(qApp->applicationDirPath());
    QString themeFilename = QString("%1.qss").arg(themeName);
    if (!themesDir.cd(m_themesDir) ||
        !themesDir.entryList().contains(themeFilename))
        return false;

    /* 打开主题文件 */
    QFile file(themesDir.absoluteFilePath(themeFilename));
    if (!file.open(QIODevice::ReadOnly))
        return false;

    /* 读取主题配置内容 */
    QTextStream in(&file);
    QString str = in.readAll();

    /* 加载主题：先清空上次样式表，否则会崩溃，qt的bug */
    //	widget->styleSheet().clear();
    widget->setStyleSheet(str);
    m_curTheme = themeName;

    /* 更新配置文件 */
    QSettings settings(m_themesIniDir, QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("UTF-8"));
    settings.setValue("cur/theme", themeName);
    emit sigChangeTheme(themeName);
    return true;
}

/* 获取可用主题列表 */
QStringList QLsThemesManager::GetThemes() const
{
    return m_themesList;
}

/* 获取当前主题 */
QString QLsThemesManager::GetCurrentTheme() const
{
    return m_curTheme;
}

/* 主题路径 */
QString QLsThemesManager::themesDir() const
{
    return m_themesDir;
}

void QLsThemesManager::setThemesDir(const QString &themesDir)
{
    if (m_themesDir == themesDir)
        return;
    m_themesDir = themesDir;
    m_themesIniDir = QString("ini/%1.ini").arg(themesDir);

    /* 更新可用主题列表 */
    RefreshLocalThemes();
}

/* 主题配置文件路径 */
QString QLsThemesManager::themesIniDir() const
{
    return m_themesIniDir;
}
